#include "general.h"
#include "ui_general.h"
#include "wizard.h"
#include <QMessageBox>

#include <QFile>
#include <QRegExp>
#include <QTextStream>
#include <QTextCodec>
#include <QTextCursor>
#include <QTextDocument>
#include <QLabel>
#include <QLineEdit>

General::General(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::General)
{
    m_ui->setupUi(this);
    db = new CDBProvider("",this);
    tb = new TextEdit(this);
    t = new TextEdit(this);
    changedAnswer = false;
    loadList();
}

General::~General()
{
    delete m_ui;
}

void General::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void General::on_pushButton_2_clicked()
{
    Wizard d(this);
    if(d.exec() == QDialog::Accepted){
        QList <int> list = db->getIdListTask(d.getIdGroup());
        if(list.isEmpty()){
            QMessageBox::information(this,trUtf8("Ошибка"),trUtf8("Нет заданий для выбранного раздела\nТесты небыли сгенерированны"));
            return;
        }
        int id = db->insertGeneral(d.getDate(),d.getNameGroup(),d.getIdSchool());        
        int id_tasks = 0;
        for(int i=0; i < d.getCount(); ++i){
            id_tasks = db->insertGeneralTasks(id);
            //foreach(int id_task,list){
                db->insertGeneralTasksTask(id_tasks,list);//id_task);
            //}
        }
    }
    loadList();
}

void General::loadList(){
    m_ui->treeWidget->clear();
    m_ui->treeWidget->addTopLevelItems(db->getGeneral());
}

void General::loadListTasks(int id){
    //m_ui->listWidget->clear();
//    QListWidgetItem *i;
//    foreach(i,db->getItemsForTasks(id)){
//        //m_ui->listWidget->addItem(i);
//    }
}

void General::on_treeWidget_itemClicked(QTreeWidgetItem* item, int column)
{
    clearAnswers();
    if(m_ui->treeWidget->currentItem()->text(2)=="tester")
        loadTasksTester(m_ui->treeWidget->currentItem()->text(0).toInt());
}

void General::on_pushButton_3_clicked()
{
    print(2);
}

void General::print(int type){
    QTreeWidgetItem *i = m_ui->treeWidget->currentItem();
    if(!i)return;
    QTextDocument * docs = new QTextDocument();
    docs->setPageSize(QSizeF(1280,1024));
    QTextDocument * docsB = new QTextDocument();
    docsB->setPageSize(QSizeF(1280,1024));
    QTreeWidgetItemIterator it(i);
    cnt = 1; bcnt = 1;
     do{         
        if ((*it)->text(2) == "tester"){
             docs = tasksPrintForGroup((*it)->text(0).toInt(),docs);
             docsB = blankPrintForGroup((*it)->text(0).toInt(),docsB);
         }
        ++it;
        if(!*it) break;
     }while ((*it)->text(5).toInt() > i->text(5).toInt());    
    t->setDocument(docs);    
    tb->setDocument(docsB);
    switch(type){
       case 0:
                t->show();
                tb->show();
                break;
       case 1:
                t->filePrint();
                tb->filePrint();
                break;
       case 2:
                t->fileSaveAs();
                tb->fileSaveAs();
                break;
    }
 }

void General::on_viewPrintTasks_clicked()
{
    print(0);
}

QTextDocument * General::tasksPrintForGroup(int id,QTextDocument * docs){

       QString temp;       
       QStringList list = db->getTaskForTasks(id);

       QFile file("template/headerTasks.html");
       if (file.open(QFile::ReadOnly)){
            QByteArray data = file.readAll();
            QTextCodec *codec = QTextCodec::codecForName("UTF-8");//QTextCodec::codecForHtml(data);
            temp = codec->toUnicode(data);
            temp.replace("<!--{SHIFR}-->",QString::number(id));
        }        
        QTextCursor * cursor = new QTextCursor(docs);
        cursor->movePosition(QTextCursor::End);
        QTextBlockFormat textFormat;        

        if(docs->pageCount()>1){
                   textFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
                   cursor->insertBlock(textFormat);
                   cnt++;
        }
        textFormat.setPageBreakPolicy(QTextFormat::PageBreak_Auto);

        cursor->insertHtml(temp);
        QRegExp reg("<body[^>]*>([\\s\\S]*)<\\/body>",Qt::CaseInsensitive);        
        delete cursor;
        foreach(QString doc,list){
              if(reg.indexIn(doc)>0){
                cursor = new QTextCursor(docs);
                cursor->movePosition(QTextCursor::End);
                textFormat.setPageBreakPolicy(QTextFormat::PageBreak_Auto);
                cursor->setBlockFormat(textFormat);
                cursor->insertHtml(reg.cap(1));
                int lcnt = cnt, lpage = docs->pageCount();

                if(cnt < docs->pageCount()){
                    docs->undo();
                    textFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
                    cursor->setBlockFormat(textFormat);
                    cursor->insertHtml(reg.cap(1));
                    cnt++;
                }
               delete cursor;
            }else{
                QMessageBox::critical(this,"ert56dsfsdf",doc);
            }
        }
       cursor = new QTextCursor(docs);
       cursor->movePosition(QTextCursor::End);
       if(cnt % 2){
           textFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
           cursor->insertBlock(textFormat);
           cnt++;
       }
       delete cursor;
       return docs;
}

QTextDocument * General::blankPrintForGroup(int idTasks,QTextDocument * docs){
     if (!QFile::exists("template/blank.html"))
         return docs;
     QFile file("template/blank.html");
     //QFileInfo fi(f);
     if (!file.open(QFile::ReadOnly))
         return docs;
     QTextCursor cursor(docs);
     cursor.movePosition(QTextCursor::End);
     QTextBlockFormat textFormat;
     QByteArray data = file.readAll();
     QTextCodec *codec = QTextCodec::codecForHtml(data);
     QString temp = codec->toUnicode(data);
     QMap<QString,QString> list = db->getDataForTasks(idTasks);
     temp.replace("<!--{SHIFR}-->",QString::number(idTasks));
     temp.replace("<!--{SCHOOL}-->",list["SCHOOL"]);
     temp.replace("<!--DATE-->",list["DATE"]);
     temp.replace("<!--{DISCIPLINE}-->",list["DISCIPLINE"]);
     temp.replace("<!--{CATALOG}-->",list["CATALOG"]);
     temp.replace("<!--{CLASS}-->",list["CLASS"]);
     temp.replace("<!--{GROUP}-->",list["GROUP"]);
     if(!list["DISABLE_B"].isEmpty()){
         temp.replace("<!--{DISABLE_B}>","");
         temp.replace("<{DISABLE_B}-->","");
     }
     if(bcnt++ > 1){
         textFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
         cursor.setBlockFormat(textFormat);
         //cursor.insertBlock();
     }
     cursor.insertHtml(temp);
     return docs;
}

QString General::blankPrint(int idTasks){
     if (!QFile::exists("template/blank.html"))
         return "";
     QFile file("template/blank.html");
     //QFileInfo fi(f);
     if (!file.open(QFile::ReadOnly))
         return "";

     QByteArray data = file.readAll();
     QTextCodec *codec = QTextCodec::codecForHtml(data);
     QString temp = codec->toUnicode(data);
     QMap<QString,QString> list = db->getDataForTasks(idTasks);
     temp.replace("<!--{SHIFR}-->",QString::number(idTasks));
     temp.replace("<!--{SCHOOL}-->",list["SCHOOL"]);
     temp.replace("<!--DATE-->",list["DATE"]);
     temp.replace("<!--{DISCIPLINE}-->",list["DISCIPLINE"]);
     temp.replace("<!--{CATALOG}-->",list["CATALOG"]);
     temp.replace("<!--{CLASS}-->",list["CLASS"]);
     temp.replace("<!--{GROUP}-->",list["GROUP"]);
     if(!list["DISABLE_B"].isEmpty()){
         temp.replace("<!--{DISABLE_B}>","");
         temp.replace("<{DISABLE_B}-->","");
     }
         return temp;
 }


void General::on_pushButton_clicked()
{
    QTreeWidgetItem * i = m_ui->treeWidget->currentItem();
    QTreeWidgetItem * p = i->parent();
    if(i){
        db->deleteGeneralTasks(i->text(1).toInt());
        delete i;
        if(p)
            if(p->childCount()<1) delete p;
    }
    return;
}

void General::on_pushButton_5_clicked()
{
    print(1);
}

void General::click_check(int state){    
    changedAnswer=true;
}

void General::on_treeWidget_clicked(QModelIndex index)
{

}

void General::loadTasksTester(int id){
    QMap <int,QMap<int,bool> > tasks = db->getTasksTester(id);
    QMapIterator <int,QMap<int,bool> > answers(tasks);    
    int i=0,y=0;
     while (answers.hasNext()) {
         QLabel * l = new  QLabel(this);
        if(i==0){
            QLabel * l = new  QLabel(this);
            l->setText(trUtf8("№"));
            l->setMaximumHeight(24);
            m_ui->gridLayoutA->addWidget(l,0,0);
            llist.append(l);
        }
         l->setText("A"+QString::number(++i));
         l->setMaximumHeight(24);
         m_ui->gridLayoutA->addWidget(l,0,i);
         llist.append(l);
         answers.next();         
         QMapIterator <int,bool> answer(answers.value());
         y = 1;
         while (answer.hasNext()) {
             answer.next();             
             if(i == 1){
                 QLabel * l = new  QLabel(this);
                 l->setText(QString::number(y));
                 l->setMaximumHeight(24);
                 m_ui->gridLayoutA->addWidget(l,y,0);
                 llist.append(l);
             }
             QCheckBox *c = new QCheckBox(this);
             c->setObjectName(QString::number(answer.key()));
             c->setChecked(answer.value());                                       
             connect(c,SIGNAL(stateChanged(int)),SLOT(click_check(int)));            
             m_ui->gridLayoutA->addWidget(c,y++,i);
             wlist.append(c);
         }
     }     
     m_ui->gridLayoutA->setVerticalSpacing(i+1);
     QMap <int,QString > tasksB = db->getTasksBTester(id);
    QMapIterator <int,QString > answerB(tasksB);
     i=0;
     while (answerB.hasNext()) {
         answerB.next();
         QLabel * l = new  QLabel(this);
         l->setText(trUtf8("B")+QString::number(++i));
         l->setMaximumHeight(24);
         l->setToolTip(QString::number(answerB.key()));
         QLineEdit *e = new QLineEdit(this);
         e->setObjectName(QString::number(answerB.key()));
         e->setText(answerB.value());         
         connect(e,SIGNAL(lostFocus()),SLOT(click_check()));
         m_ui->formLayoutB->addRow(l,e);
         llistB.append(l);
         wlistB.append(e);
     }
}


void General::clearAnswers(){
    foreach(QWidget *w,wlist){
            m_ui->gridLayoutA->removeWidget(w);
            w->~QWidget();
    }
    wlist.clear();
    foreach(QWidget *w,llist){
            m_ui->gridLayoutA->removeWidget(w);
            w->~QWidget();
    }
    llist.clear();
    foreach(QWidget *w,wlistB){
            m_ui->formLayoutB->removeWidget(w);
            w->~QWidget();
    }
    wlistB.clear();
    foreach(QWidget *w,llistB){
            m_ui->formLayoutB->removeWidget(w);
            w->~QWidget();
    }
    llistB.clear();
}

void General::on_treeWidget_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
    if(previous)
        if(previous->text(2) == "tester")
            saveTasksTester(previous->text(0).toInt());
    clearAnswers();
    if(current)
         if(current->text(2)=="tester")
             loadTasksTester(current->text(0).toInt());
}

void General::saveTasksTester(int id){
    QList <int> id_answer;
    QMap    <int,QString> answerB;
    if(changedAnswer){
        foreach(QCheckBox * c, wlist){
            if(c->checkState() == Qt::Checked) id_answer.append(c->objectName().toInt());
        }
        db->insertAnswerTesterA(id,id_answer);
        foreach(QLineEdit *e ,wlistB)
            answerB.insert(e->objectName().toInt(),e->text());
        db->insertAnswerTesterB(id,answerB);
    }
    changedAnswer =false;
}
